/*
 * @FilePath: upload.js
 * @Author: 'Giovan'
 * @Date: 2023-12-19 09:21:15
 * @LastEditors: Giovan
 * @LastEditTime: 2024-01-09 13:25:12
 */
let express = require('express');
let router = express.Router();
let path = require("path");
const Images = require('images');

let fs = require('fs');

const multer = require('multer');
// 临时上传目录
let upload = multer({ dest: 'uploads_files' });

let baseURL = require('../../../../config/upload.config').baseURL;

// /**
//  * 提供文件上传服务
//  * @route POST /api/public/web/upload
//  * @group 文件上传（公共） - 上传图片接口
//  * @param {file} file.query.required - 图片
//  * @returns {object} 200 - 返回结果对象：文件地址 url，暂存地址 tmp_path
//  * @returns {object} 605 - 请求失败
//  * @returns {Error}  default - Unexpected error
//  */
// router.post("/", upload.single('file'), function (req, res, next) {
//     let fileExtArray = req.file.originalname.split(".");
//     let ext = fileExtArray[fileExtArray.length - 1];
//     let targetPath = req.file.destination + '/' + req.file.filename + "." + ext;
//     let imgName = req.file.filename + "." + ext;
//     let mimetype = req.file.mimetype;
//     let mineTypeMap = ['text/html', 'text/xml', 'text/plain',]
//     let resUrl = baseURL + '/api/public/admin/getFiles' + '?id=' + imgName + '&&mimetype=' + mimetype
//     let resUrlFile = baseURL + '/api/public/admin/getFiles' + '?id=' + imgName + '&&mimetype=' + mimetype + '&&charset=utf-8'
//     // console.log(req.file)
//     fs.rename(path.join(process.cwd(), "/" + req.file.path), path.join(process.cwd(), targetPath), function (err) {
//         if (err) {
//             return res.sendResult({ data: null, code: 605, message: '上传文件失败' })
//         }
//         // 压缩图片
//         Images(targetPath)
//             .size(1000) // 设置目标宽度（这里设置为800像素，可以根据需求调整）
//             .save(targetPath, { quality: 80 }); // 保存压缩后的图片（quality表示压缩质量，范围为0到100，数值越大表示质量越好）

//         return res.sendResult({
//             data: {
//                 "tmp_path": targetPath,
//                 "url": mineTypeMap.includes(mimetype) ? resUrlFile : resUrl
//             }, code: 200, message: '上传成功'
//         })
//     })
// });

// router.delete("/", function (req, res, next) {
//     const filename = req.query.filename;
//     if (!filename) {
//         return res.sendResult({ data: null, code: 400, message: "未提供文件名" });
//     }
//     const filePath = path.join(process.cwd(), "uploads_files", filename);
//     fs.unlink(filePath, function (err) {
//         if (err) {
//             return res.sendResult({ data: null, code: 500, message: "删除文件失败" });
//         }
//         return res.sendResult({ data: null, code: 200, message: "删除文件成功" });
//     });
// });
// 七牛云模块
const qiniu = require('qiniu')
let accessKey = 'vfL7xnFfjXqMqpuGd3-PYY6ksiih9kBJLjdF4bGF';//可在个人中心查看
let secretKey = 'XnxuztgYxwFtDZJQQADicohDHOgHgaDuxKomf5Bh';//可在个人中心查看
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
let options = {
    scope: 'giovan', //空间的名字
};
let putPolicy = new qiniu.rs.PutPolicy(options);
let uploadToken = putPolicy.uploadToken(mac);
let config = new qiniu.conf.Config();
// 空间对应的机房
config.zone = qiniu.zone.Zone_z1;//华东区
// 是否使用https域名
config.useHttpsDomain = true;
// 上传是否使用cdn加速
config.useCdnDomain = true;
const baseUrl = 'http://qiniu.giovan.top/' //七牛云空间访问的域名
//七牛云 - 对象存储 - 图片上传
// 上传图片
router.post('/', multer({ dest: "./public/img/", }).array("file", 1), function (req, res, next) {
    let files = req.files;
    let file = files[0];
    let name = Date.now().toString()
    let suffix = '.png'
    let path = "./public/img/" + name + suffix;
    fs.renameSync("./public/img/" + file.filename, path);
    let localFile = path;
    let formUploader = new qiniu.form_up.FormUploader(config);
    let putExtra = new qiniu.form_up.PutExtra();
    let key = name + suffix;
    // 文件上传
    formUploader.putFile(uploadToken, key, localFile, putExtra,
        function (respErr, respBody, respInfo) {
            if (respErr) {
                throw respErr;
            }
            if (respInfo.statusCode == 200) {
                res.json({
                    status: '200',
                    result: {
                        path: baseUrl + respBody.key
                    },
                    msg: 'ok'
                })
            } else {
                res.json({
                    status: '-1',
                    result: {},
                    msg: '上传失败'
                })
            }
            fs.unlinkSync(path);
        });
})
router.delete("/", function (req, res, next) {
    const regex = /filename=([^&]+)/;
    const match = req.url.match(regex);
    var key = match[1]
    console.log(match[1]);
    var bucketManager = new qiniu.rs.BucketManager(mac, config);
    var bucket = 'giovan'
    bucketManager.delete(bucket, key, function (err, respBody, respInfo) {
        if (err) {
            res.json({
                data: null,
                meta: {
                    msg: '删除失败',
                    status: '500',
                }

            })
        } else {
            res.json(
                {
                    data: null, meta: {
                        status: 200, message: '删除成功'
                    }
                }

            )
        }
    });

});
module.exports = router;
